package cn.itsource.system.controllor;

import cn.itsource.system.domain.Role;
import cn.itsource.system.query.RoleQuery;
import cn.itsource.system.service.RoleService;
import cn.itsource.util.AjaxResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/role")
public class RoleController {
    
    @Autowired
    private RoleService roleService;

    /**
     * 新增或修改
     * @param r
     * @return
     */
    @PostMapping
    public AjaxResult save(@RequestBody Role r){
        if (r.getId()==null){
            roleService.insert(r);
            //菜单和角色
            roleService.savaRoleMenus(r);
            //权限和角色
            roleService.savaPermissions(r);
            return AjaxResult.ok();
        }else {
            //先删除在添加 修改
            roleService.deleteRoleMenus(r.getId());
            roleService.deleteRolePermissions(r.getId());
            //添加修改
            roleService.updateByPrimaryKeySelective(r);
            //判斷是否爲空
            if (r.getMenusId().size() != 0) {
                //菜单和角色
                roleService.savaRoleMenus(r);
            }
            if (r.getPermissionsId().size() != 0) {
                //权限和角色
                roleService.savaPermissions(r);
            }
            return AjaxResult.ok();
        }
    }
    



    /**
     * 分页查询
     * @param roleQuery
     * @return
     */
    @PatchMapping
    public AjaxResult pageInfo(@RequestBody RoleQuery roleQuery){
        try {
            return AjaxResult.ok(roleService.pageInfo(roleQuery));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    /**
     * 批量删除
     * @param r
     * @return
     */
    @PatchMapping("/batchDeletion")
    public AjaxResult batchDeletion(@RequestBody List<Role> r){
        try {
            roleService.deleteAll(r);
            return AjaxResult.ok();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    /**
     * 根据id删除
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    public AjaxResult delete(@PathVariable("id") Long id){
        try {
            roleService.deleteByPrimaryKey(id);
            return AjaxResult.ok();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


}
